<?php

namespace App\Controller;

use App\Logic\ImLogic;
use App\Middleware\AuthMiddleware;
use App\Model\User;
use Exception;
use Hyperf\Context\Context;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Psr\Http\Message\ResponseInterface;

#[AutoController]
class ImController extends AbstractController
{
    /**
     * 获取会话列表
     * @return ResponseInterface
     */
    public function conversation(): ResponseInterface
    {
        $this->parseToken();
        $userid = Context::get('userid', 0);
        $conversation = ImLogic::getConversation($userid);
        return $this->apiReturn(200, 'succ', $conversation);
    }

    /**
     * 删除会话
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function delConversation(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $sessionId = $this->request->input('sessionId', '');
        if (empty($sessionId) || !ImLogic::getTargetUserId($sessionId, $userid)) {
            return $this->apiReturn(400, '会话ID异常');
        }
        ImLogic::delConversation($userid, $sessionId);
        return $this->apiReturn(200, '删除成功');
    }

    /**
     * 获取会话详情
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function chatInfo(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $targetUserId = (int)$this->request->input('userId', 0);
        if (!$targetUserId) {
            return $this->apiReturn(400, '会话异常');
        }
        try {
            $info = ImLogic::getChatInfo($userid, $targetUserId);
            return $this->apiReturn(200, 'succ', $info);
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 消息列表
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function msgList(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $input = $this->request->all();
        if (!isset($input['userId']) || !intval($input['userId'])) {
            return $this->apiReturn(400, '会话异常');
        }
        $data = ImLogic::getMessageList($userid, intval($input['userId']), $input);
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 好友申请
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function apply(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $targetImId = (int)$this->request->input('targetImId', 0);
        $targetUserId = (int)$this->request->input('targetUserId', 0);
        if (!$targetUserId || !$targetImId) {
            return $this->apiReturn(400, '参数错误');
        }
        $message = $this->request->input('message', '');
        try {
            ImLogic::applyFriend($userid, $targetImId, $targetUserId, $message);
            return $this->apiReturn(200, '申请提交成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 处理好友申请
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function doApply(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $applyId = (int)$this->request->input('applyId', 0);
        $operate = (int)$this->request->input('operate', 0);
        try {
            ImLogic::doApply($userid, $applyId, $operate);
            return $this->apiReturn(200, '操作成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 所有申请列表
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function applyList(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $data = ImLogic::applyList($userid, $this->request->all());
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 搜索用户
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function search(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $keyword = $this->request->input('keyword', '');
        if (empty($keyword)) {
            return $this->apiReturn(400, '请输入搜索关键词');
        }
        try {
            $data = ImLogic::searchUser($userid, $keyword);
            return $this->apiReturn(200, 'succ', $data);
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 添加好友检测
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function checkAddUserFriend(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $targetImId = (int)$this->request->input('imId', 0);
        $targetUserId = (int)$this->request->input('userId', 0);
        $status = true;
        if (!$targetUserId && $userid != $targetUserId && !ImLogic::isFriend($userid, $targetUserId)) {
            $status = false;
        }
        $userInfo = User::query()->where(['id' => $targetUserId, 'im_id' => $targetImId])->select(['id', 'im_id', 'nickname'])->first();
        if (!$userInfo) {
            return $this->apiReturn(400, '用户不存在');
        }
        return $this->apiReturn(200, 'succ', [
            'imId' => $userInfo['im_id'],
            'userId' => $userInfo['id'],
            'userNick' => $userInfo['nickname'],
            'userAvatar' => img_url($userInfo['avatar'], 100),
            'checkStatus' => $status
        ]);
    }

    /**
     * 获取通讯录
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function contacts(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $data = ImLogic::getContact($userid);
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 备注昵称
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function remarkNick(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $friendUserId = $this->request->input('friendUserId', 0);
        $nickname = $this->request->input('nickname', '');
        if (!$friendUserId || empty($nickname)) {
            return $this->apiReturn(400, '参数错误');
        }
        ImLogic::remarkNick($userid, $friendUserId, $nickname);
        return $this->apiReturn(200, '设置成功');
    }

    /**
     * 获取黑名单
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function blackList(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $data = ImLogic::getBlackList($userid, $this->request->all());
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 解除拉黑
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function delBlackUser(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $targetUserId = $this->request->input('userId', 0);
        if (!$targetUserId) {
            return $this->apiReturn(400, '参数错误');
        }
        ImLogic::delBlackUser($userid, $targetUserId);
        return $this->apiReturn(200, '操作成功');
    }

    /**
     * 拉黑用户
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function addBlackUser(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $targetUserId = $this->request->input('userId', 0);
        if (!$targetUserId) {
            return $this->apiReturn(400, '参数错误');
        }
        try {
            ImLogic::setBlackUser($userid, $targetUserId);
            return $this->apiReturn(200, '操作成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 获取系统消息列表
     * @return ResponseInterface
     */
    public function sysMsgList(): ResponseInterface
    {
        $this->parseToken();
        $userid = Context::get('userid', 0);
        $data = ImLogic::sysMsgList($userid, $this->request->all());
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 获取系统消息详情
     * @return ResponseInterface
     */
    public function sysMsgDetail(): ResponseInterface
    {
        $this->parseToken();
        $userid = Context::get('userid', 0);
        $msgId = (int)$this->request->input('msgId', 0);
        if (!$msgId) {
            return $this->apiReturn(400, '参数错误');
        }
        try {
            $data = ImLogic::sysMsgDetail($userid, $msgId);
            return $this->apiReturn(200, 'succ', $data);
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 获取好友资料
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function getFriendProfile(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $targetUserId = $this->request->input('userId', 0);
        if (!$targetUserId) {
            return $this->apiReturn(400, '参数错误');
        }
        try {
            $data = ImLogic::getProfile($userid, $targetUserId);
            return $this->apiReturn(200, 'succ', $data);
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 设置备注
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function setNickName(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $targetUserId = $this->request->input('userId', 0);
        $nickname = $this->request->input('nickName', '');
        if (!$targetUserId) {
            return $this->apiReturn(400, '参数错误');
        }
        try {
            ImLogic::setNickName($userid, $targetUserId, $nickname);
            return $this->apiReturn(200, 'succ', ['remarkNickName' => $nickname]);
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }
    #[Middleware(AuthMiddleware::class)]
    public function delFriend(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $targetUserId = $this->request->input('userId', 0);
        if (!$targetUserId) {
            return $this->apiReturn(400, '参数错误');
        }
        ImLogic::delFriend($userid, $targetUserId);
        return $this->apiReturn();
    }
}